package com.zyz.I_多线程.Lock锁;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: vick
 * @Date: 2025/3/24
 * @Description:
 * @version: 1.0
 */
public class Demo2 implements Runnable {
    int ticket = 10;

    //1. 创建Lock实例，必须保证多个线程共享同一个Lock实例
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try {
                //2. 调用lock(), 实现共享代码的锁定
                lock.lock();

                if (ticket > 0) {
                    Thread.sleep(10);
                    System.out.println(ticket--);
                }else {
                    break;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                //3. 调用unlock（），释放共享代码的锁定
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        Demo2 demo2 = new Demo2();
        Thread thread1 = new Thread(demo2);
        Thread thread2 = new Thread(demo2);
        thread1.start();
        thread2.start();
    }
}
